package com.zhuoan.im.webapp.common.thread;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * ThreadPoolManager
 *
 * @author weixiang.wu
 * @date 2018-04-09 21:40
 **/
public class ThreadPoolHelper {

    public static  ExecutorService executorService = new ThreadPoolExecutor(8, 64,
        60L, TimeUnit.SECONDS,
        new LinkedBlockingQueue<Runnable>(200),
        new ThreadFactoryBuilder().setNameFormat("call-back-handle-pool-%d").build(),
        new ThreadPoolExecutor.CallerRunsPolicy());


    //让可执行程序休息一下
    private static int executePrograms = 0;
    private static int produceTaskMaxNumber = 100;

    public static void main(String[] args) {
        // 构造一个线程池
        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(2, 4, 3,
            TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(3),
            new ThreadPoolExecutor.CallerRunsPolicy());
        long l = System.currentTimeMillis();
        for (int i = 1; i <= produceTaskMaxNumber; i++) {
            try {
                String task = "task@ " + i;
                System.out.println("put " + task);
                threadPool.execute(new ThreadPoolTask(task));

                // 便于观察，等待一段时间
                Thread.sleep(executePrograms);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        System.err.println(System.currentTimeMillis()-l);
    }
}
